<script setup>
import { storeToRefs } from 'pinia';
import { ref } from 'vue';
import dayjs from 'dayjs';

const { params } = useRoute();
console.log("params.id: ", params.id);

const container_input = ref("");
const inputFieldCont = ref("");
const mpp = useCookie('mpp');
const counter = useStoreCounter();
const urlHome = useUrl();
const urlCutHome = urlHome.value.substring(0, urlHome.value.length - 5);
const image_link = useModalImage();
const enableFinish = ref(true);
image_link.value = '';
const isOpen = ref(false);
const contSelect = ref('');
const isFree = ref(false);

const kom_edited = ref('');
// const file = ref(null);


const { data: oneNar } = await useFetch(`${urlHome.value}lab/one_nar`, {
	query: {
		naryad_id: params.id,
	}
})


const { data: imgList, refresh: imgListRefresh } = await useFetch(`${urlHome.value}lab/image_list/`, {
	watch: [oneNar],
	query: {
		naryad_id: params.id
	}
})


const handleFileSelection = async (event) => {
	let formData = new FormData();
	// console.log("files", event[0])
	// let uploadedFile = event.target.files[0];
	console.log(event[0]);
	// file.value = uploadedFile;
	formData.append('image', event[0])
	formData.append('naryad_id', params.id)
	console.log("image_add: ", `${urlHome.value}lab/image_add/`)
	const response = await $fetch(`${urlHome.value}lab/image_add/`, {
		headers: {
			'Access-Control-Allow-Credentials': true,
			'Access-Control-Allow-Origin': '*',
			'Access-Control-Allow-Methods': 'POST',
			'Access-Control-Allow-Headers': 'application/json',
		},
		method: 'POST',
		body: formData
	})
	if (response.ok) {
		imgListRefresh();
	} else {
		alert("Ошибка загрузки изображения")
	}
	return;
}


const enableContainer = computed(() => contSelect.value > 0 || (0 <= container_input.value <= 1000 && isFree.value) || oneNar.value.naryad.id_etap > 0 ? true : false)

const finishButton = computed(() => enableContainer.value && enableFinish.value ? true : false)

watchDebounced(
	inputFieldCont,
	() => {
		console.log(container_input.value, inputFieldCont.value)
		if (container_input.value !== inputFieldCont.value) {
			isFreeFetch()
		} else {
			console.log("равны")
		}
		// isFree.value = isContainerFree.value
	},
	{ debounce: 500, maxWait: 1000 },
)

const { data: isContainerFree, refresh: isFreeFetch } = await useFetch(`${urlHome.value}lab/get_container`, {
	immediate: false,
	// watch: [container_input],
	query: {
		container: container_input
	},
	onResponse({ request, response, options }) {
		isFree.value = response._data
		container_input.value = inputFieldCont.value
	}
})

const { data: comments_list, refresh: comListRefresh } = await useFetch(`${urlHome.value}lab/comments_list`, {
	query: {
		naryad_id: params.id
	}
})


function openModalImage(image_url) {
	isOpen.value = true;
	image_link.value = image_url;
}


async function saveKom() {
	let formData = new FormData();
	formData.append('comment', kom_edited.value)
	formData.append('naryad_id', params.id)
	formData.append('mpp', mpp.value)

	const response = await $fetch(`${urlHome.value}lab/add_comment`, {
		method: 'POST',
		body: formData
	})
	if (response.ok) {
		console.log(response.status);
		kom_edited.value = ''
		comListRefresh();
	} else {
		alert("Ошибка сохранения комментария " + response.message);
	}
}


async function moveTo(id, sdl) {
	enableFinish.value = false
	console.log("id: ", id, " sdl: ", sdl, " mpp: ", mpp.value)
	if (oneNar.value.naryad.id_etap == 0) {
		const response = await $fetch(`${urlHome.value}lab/move_naryad`, {
			query: {
				naryad_id: id,
				sdl: sdl,
				mpp: mpp.value,
				container: container_input.value,
			}
		})
		if (response.ok) {
			console.log(response.status);
			await navigateTo('/lab/naryad_list');
		}
	} else {
		console.log("move else")
		const response = await $fetch(`${urlHome.value}lab/move_naryad`, {
			query: {
				naryad_id: id,
				sdl: sdl,
				mpp: mpp.value,
			}
		})
		if (response.ok) {
			console.log(response.status);
			await navigateTo('/lab/naryad_list');
		}
	}
}



async function finishNaryad(id) {
	enableFinish.value = false

	const response = await $fetch(`${urlHome.value}lab/naryad_close`, {
		query: {
			naryad_id: id,
		}
	})

	if (response.ok) {
		console.log(response.status);
		await navigateTo('/lab/naryad_list');
	} else {
		alert("Ошибка передачи наряда " + response.message);
	}

}

async function setContainer() {
	if (contSelect.value !== '') {
		container_input.value = contSelect.value
		inputFieldCont.value = contSelect.value
		isFree.value = true
	} else {
		container_input.value = ''
		inputFieldCont.value = ''
	}
}
</script>

<template>
	<div>
		<div>
			<div class="px-2 grid lg:grod-cols-2 md:grid-cols-2 sm:grid-cols-1">
				<div class="form-label">Пациент: <b>{{ oneNar?.naryad?.patient?.fam }} {{ oneNar?.naryad?.patient?.im }}
						{{ oneNar?.naryad?.patient?.ot }}</b></div>
				<div class="form-label">Дата рождения: <b>{{ oneNar?.naryad?.patient?.dr ?
					dayjs(oneNar.naryad.patient.dr).format('DD.MM.YYYY') : "" }}</b></div>
				<div class="form-label">Дата наряда: <b>{{ oneNar?.naryad?.dou ?
					dayjs(oneNar.naryad.dou).format('DD.MM.YYYY') : "" }}</b></div>
				<div class="form-label">Оплата: <b>{{ oneNar?.naryad?.opl?.name_opl }}</b></div>
				<div class="form-label">Номер квитанции: <b>{{ oneNar?.naryad?.nkv }}</b></div>
				<div class="form-label">Стоимость: <b>{{ oneNar?.naryad?.stu ? (oneNar?.naryad?.stu).toLocaleString() :
					""
						}} р.</b></div>
				<div class="form-label">Врач: <b> {{ oneNar?.naryad?.naryad_doc?.user ?
					`${oneNar?.naryad?.naryad_doc?.user?.fam} ${oneNar.naryad.naryad_doc.user.im}
						${oneNar.naryad.naryad_doc.user.ot}` : "" }}
					</b>
				</div>
				<div v-if="oneNar?.naryad?.id_etap > 1" class="form-label">
					Контейнер: <b>{{ oneNar?.naryad?.container?.id }}</b>
				</div>
			</div>
		</div>
		<br>
		<UInput color="green" type="file" accept="image/*" @change="handleFileSelection($event)"
			class="px-2 file-input w-full md:max-w-xs lg:max-w-xs xs:max-w-lg" />
		<br>
		<div class="px-2 grid grid-cols-4 gap-2 md:grid-cols-5 lg:grid-cols-5" v-auto-animate>
			<div v-for="image in imgList" :key="image">
				<img :src="urlCutHome + image" @click="openModalImage(image)" alt="image" class="w-16 md:w-24 lg:w-28">
			</div>
		</div>
		<div class="form-control px-2">
			<UInput v-model="kom_edited" @keyup.enter="saveKom" class="max-w-xs" color="primary" variant="outline"
				placeholder="Введите комментарий" />
			<UButton class="btn btn-sm my-1" v-if="kom_edited.length > 0" @click="saveKom">
				Добавить
				комментарий</UButton>
		</div>
		<div v-if="oneNar.naryad.id_etap === 0">
			<div class="mb-2 px-2 py-2 text-lg font-semibold text-gray-900 dark:text-white">
				Номер контейнера:
				<UInput color="primary" class="max-w-xs" v-model.number="inputFieldCont" :disabled="contSelect > 0" />
			</div>
			<div v-if="container_input > 1000 || container_input == ''" class="px-2 alert alert-error shadow-lg">
				<UAlert title="Неверный номер" icon="i-heroicons-command-line" color="orange" variant="soft" />
			</div>
			<div v-else-if="contSelect === '' && container_input <= 1000 && isFree == false"
				class="px-2 alert alert-error shadow-lg">
				<UAlert title="Контейнер занят" icon="i-heroicons-command-line" color="orange" variant="soft" />
			</div>
			<div v-if="oneNar?.nar_containers?.length > 0" class="px-2">
				<div>Прикрепить к другому наряду:</div>
				<select v-model="contSelect" @change="setContainer"
					class="select border border-green-500 rounded-lg color select-bordered max-w-xs ">
					<option value="">Указать контейнер вручную</option>
					<option v-for="naryad in oneNar.nar_containers" :key="naryad['nkv']"
						v-bind:value="naryad['container__id']">
						№ {{ naryad['nkv'] }} от {{ dayjs(naryad['dou']).format('DD.MM.YYYY') }} на сумму {{
							naryad['stu'] ? (naryad['stu']).toLocaleString() : "" }}
					</option>
				</select>
			</div>
		</div>
		<br>
		<div class="flex justify-center">
			<div v-if="oneNar?.naryad?.sdl_etap?.sdl === 1 && oneNar?.naryad?.id_etap > 2 || oneNar?.naryad?.sdl_etap?.sdl === 1000 && oneNar?.naryad?.id_etap > 2"
				:disabled="!finishButton">
				<UButton size="md" :block="false" @click="finishNaryad(oneNar?.naryad?.id)">
					<img src="/img/finish.svg" width="36" />
					Закрыть наряд
				</UButton>
			</div>
			<div class="px-2"
				v-if="oneNar?.naryad?.sdl_etap?.sdl !== 1 && oneNar?.naryad?.sdl_etap?.sdl !== 35 && oneNar?.naryad?.sdl_etap?.sdl !== 3500 && oneNar?.naryad?.id_etap > 2">
				<UButton @click="moveTo(oneNar?.naryad?.id, 35)" :disabled="!finishButton">
					<NaryadListMoveTech />
					Передать технику
				</UButton>
			</div>
			<div class="px-2" v-if="oneNar?.naryad?.sdl_etap?.sdl === 1 || oneNar?.naryad?.sdl_etap?.sdl === 1000">
				<UButton @click="moveTo(oneNar?.naryad?.id, 35)" :disabled="!finishButton">
					<NaryadListMoveTech></NaryadListMoveTech>
					Передать в лабораторию
				</UButton>
			</div>
			<div class="flex gap-2"
				v-if="(oneNar?.naryad?.sdl_etap?.sdl === 35 || oneNar?.naryad?.sdl_etap?.sdl === 3500) && oneNar?.naryad?.id_etap >= 2">
				<UButton @click="moveTo(oneNar?.naryad?.id, 1)" :disabled="!finishButton">
					<NaryadListMoveDoc />
					Врачу
				</UButton>
				<UButton @click="moveTo(oneNar?.naryad?.id, 36)" :disabled="!finishButton">
					<NaryadListMovePol />
					Полировщику
				</UButton>
				<UButton @click="moveTo(oneNar?.naryad?.id, 37)" :disabled="!finishButton">
					<NaryadListMoveLit />
					Литейщику
				</UButton>
				<UButton @click="moveTo(oneNar?.naryad?.id, 38)" :disabled="!finishButton">
					<NaryadListMoveCad />
					Cad/Cam
				</UButton>
			</div>
		</div>
		<div class="flex justify-around">
			<div>
				<div class="px-2">Предыдущие этапы выполняли:</div>
				<ul class="steps steps-vertical px-2" v-auto-animate>
					<li v-for="item in oneNar.prev_etaps" class="step step-neutral break-word" :key="item.id">
						<div class="text-left w-full">
							<b>{{ item?.sdl?.name_sdl }}
								{{ item.user && item.user.fam ? item.user.fam : "" }} {{ item.user && item.user.im ?
									item.user.im[0] : "" }}. {{
									item.user && item.user.ot ? item.user.ot[0] : ""
								}}.</b>
							<br>
						</div>
					</li>
					<li v-if="oneNar?.naryad?.user_etap_link?.login === 'none'" data-content="!"
						class="step step-error">
						Не назначен
					</li>
					<li v-else class="step step-accent">
						<b>
							{{ oneNar?.naryad?.sdl_oneNar?.naryad?.name_sdl }}
							{{ oneNar.naryad.user_etap_link && oneNar.naryad.user_etap_link.fam ?
								oneNar.naryad.user_etap_link.fam : "" }}
							{{ oneNar?.naryad?.user_etap_link?.im[0] }}.
							{{ oneNar?.naryad?.user_etap_link?.ot[0] }}.
						</b>
					</li>
				</ul>
			</div>
			<div>
				Комментарии:
				<ul>
					<li v-for="comment in comments_list">
						<i><sub>{{ dayjs(comment.date).format('DD MMM HH:mm') }}</sub></i>
						{{ comment?.naryad?.sdl_etap?.name_sdl }} <b>{{ comment?.user?.fam }} {{
							comment?.user?.im[0] }}. {{
								comment?.user?.ot[0] }}.</b> - {{
								comment?.comment }}
					</li>
				</ul>
			</div>
		</div>
		<UModal v-model="isOpen">
			<UCard size="">
				<NuxtImg :src="urlCutHome + image_link.value" alt="image" sizes="100vw sm:50vw md:400px" />
			</UCard>
		</UModal>
	</div>
</template>